package zhongbo.java.air.airmonitor.web.websocket;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket/alert")
@Component
@Slf4j
public class AlertZoneWebSocket {

    public final static ConcurrentHashMap<Session, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session, session);
        log.info("WebSocket连接建立成功！");
    }

    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session);
        log.info("WebSocket连接关闭！");
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("接收到客户端消息：" + message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.info("WebSocket发生错误！");
    }

    public static void sendMessage(String message) {
        for (Session session : sessionMap.values()) {
            if (!session.isOpen()){
                continue;
            }
            synchronized (session){
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
